package org.grow.linyi.service;

import org.grow.linyi.dao.JpaMainBlog;
import org.grow.linyi.entity.MainBlog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.transaction.Transactional;
import java.time.LocalDate;
import java.time.LocalDateTime;

@Service
public class BlogService {
    @Autowired
    private JpaMainBlog jpaMainBlog;
    @Value("${app.author}")
    private String author;
    public void saveBlog(String title,String content){
        MainBlog blog = new MainBlog();
        blog.setId(null);
        blog.setCreateTime(LocalDateTime.now());
        blog.setAuthor(author);
        blog.setBrowseNum(0);
        blog.setBrowseNum(0);
        blog.setTitle(title);
        blog.setContent(content);
        blog.setShortContent(content.substring(0,50));
        System.out.println(blog);
        jpaMainBlog.save(blog);
    }
    @Autowired
    private EntityManager entityManager;
    @Transactional
    public MainBlog browser(Long id){
        MainBlog blog = jpaMainBlog.findById(id).get();
        System.out.println("start : "+blog.getCreateTime());
        if(null!=blog){

            blog.setBrowseNum(blog.getBrowseNum()+1);
            entityManager.persist(blog);
//            blog = jpaMainBlog.save(blog);
        }
        System.out.println("stop : "+blog.getCreateTime());
        return blog;
    }

}
